package com.cwits.wifi.ui.service;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;

import com.cwits.wifi.tool.FileUtil;
import com.cwits.wifi.util.Dbug;
import com.cwits.wifi.util.IAction;
import com.cwits.wifi.util.TimeFormater;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhanghua on 2016/5/18.
 * 编码服务
 */
public class EncodeAVIToMP4Service extends Service {
    private static long mCurrentEncodeTime = 0L;//记录每一个视频的开始编码时间
    private String tag = this.getClass().getSimpleName();
    private static boolean mIsEncoding = false;//是否开始编码
    private static List<String> mEncodeList = new ArrayList<String>();
    private static EncodeAVIToMP4Service instance = null;
    private static String mCurrentEncodePath;//当前编码视频路径
    private Handler mHandler;
    private static EncodeAVIToMP4Thread mEncodeAVIToMP4Thread = null;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 首次启动编码服务回调，加入没有编码完成的视频avi
     */
    @Override
    public void onCreate() {
        super.onCreate();
        mIsEncoding = false;
        FileUtil.deleteAllChildFile(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/lipeibao/168cardev/avi2mp4"));
        _addNoAVIToMP4();
        Dbug.i(tag, "------onCreate-----");
    }

    /**
     * 结束编码服务，清空数据
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mEncodeList != null)
            mEncodeList.clear();
        mIsEncoding = false;
        Dbug.i(tag, "------onDestroy-----");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Dbug.i(tag,"------onStartCommand-----");
        startEncode();
        return START_STICKY;
    }

    /**
     * 将需要编码的视频加入到列表中
     * @param avi_path 需编码的视频路径
     */
    public static void addEncodeAVI(String avi_path){
        if(mEncodeList.size() > 0){
            boolean flag = false;
            for(int i = 0;i < mEncodeList.size();i++){
                if(mEncodeList.get(i).equals(avi_path)){
                    flag = true;
                    break;
                }
            }
            if(!flag)
                mEncodeList.add(avi_path);
        }else{
            mEncodeList.add(avi_path);
        }
        Dbug.i("EncodeAVIToMP4Service", "------addEncodeAVI-----avi_path:" + avi_path);
    }

    /**
     * 是否正在编码
     * @return
     */
    public static boolean getIsEncoding()
    {
        return mIsEncoding;
    }

    /**
     * 获取当前编码路径
     * @return
     */
    public static String getCurrentEncodePath(){
        if(mIsEncoding){
            return mCurrentEncodePath;
        }else{
            return null;
        }
    }

    /**
     * 获取当前编码视频的开始编码时间
     * @return
     */
    public static long getCurrentEncodeTime(){
        return mCurrentEncodeTime;
    }

    /**
     * 启动编码
     */
    private void startEncode(){
        if(!mIsEncoding&&mEncodeList.size() > 0){
            mEncodeAVIToMP4Thread = new EncodeAVIToMP4Thread();
            mEncodeAVIToMP4Thread.start();
            Dbug.i(tag, "------Encode-----end");
        }
    }

    /**
     * 发送广播
     */
    private void sendEncordSuccessBroadcast(){
        Intent sucess = new Intent(IAction.ACTION_ENCORDING_SUCCESS);
        this.sendBroadcast(sucess);
        Dbug.i(tag,"--------sendEncordSuccessBroadcast-----");
    }

    /**
     * 发送当前编码状态广播
     * @param current_path
     * @param action
     */
    private void sendEncodeCurrentBroadcast(String current_path,String action){
        Intent sucess = new Intent(action);
        sucess.putExtra(action, current_path);
        this.sendBroadcast(sucess);
        Dbug.i(tag,"--------sendEncordCurrentSuccessBroadcast-----current_path:" + current_path + "---action:" + action);
    }

    /**
     * 编码接口
     */
    private void encoding(){
        mIsEncoding = true;
        while(mEncodeList.size() > 0){
            if(!mIsEncoding)
                break;
            String avi_path = mEncodeList.get(0);
            if(!isExist(avi_path)){
                mEncodeList.remove(0);
                continue;
            }
            mCurrentEncodeTime = System.currentTimeMillis();
            sendEncodeCurrentBroadcast(avi_path, IAction.ACTION_ENCORDING_CURRENT_START);
            mCurrentEncodePath = avi_path;
            int indef = avi_path.lastIndexOf(".");
            int lastindex = avi_path.lastIndexOf("/");
            String avimp4_name = avi_path.substring(lastindex + 1, indef);
            String avimp4_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/lipeibao/168cardev/avi2mp4/" + avi_path.substring(lastindex + 1,indef) + ".mp4";
            Dbug.i(tag, "-------avimp4_path:" + avi_path.substring(lastindex,indef));
            String mp4_dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/lipeibao/168cardev/mp4";
            Dbug.i(tag, "-------mp4_path:" + mp4_dir);
            String ffpegcode = "ffmpeg -i " + avi_path + " -c:v libx264 -preset ultrafast -crf 29 -r 25 -s 800*450 " + avimp4_path;
            Dbug.i(tag,"-------ffpegcode:" + ffpegcode);

            int index = ffpegcode.lastIndexOf(" ");
            String startpath = ffpegcode.substring(index + 1, ffpegcode.length());
            final String[] argv=ffpegcode.split(" ");
            final Integer argc=argv.length;

            try{
                Dbug.i(tag,"-------ffmpegcore_start-------time:" + TimeFormater.formatYMDHMS(System.currentTimeMillis()));
                int i = com.leixiaohua1020.sffmpegandroidtranscoder.MainActivity.ffmpegcore(argc,argv);
                Dbug.i(tag,"-------ffmpegcore_end:" + i + "---time:" + TimeFormater.formatYMDHMS(System.currentTimeMillis()));
                if(i == 0){
                    //编码成功
                    FileUtil.renameFile(avimp4_path,mp4_dir,avimp4_name + ".mp4");
                    Dbug.i(tag, "-----renameFile----success------");
                }else{
                    //编码失败
                }
            }catch (Exception e){
                //编码失败
                mEncodeList.remove(0);
                continue;
            }
            mEncodeList.remove(0);
            sendEncodeCurrentBroadcast(avi_path, IAction.ACTION_ENCORDING_CURRENT_END);
        }
        Dbug.i(tag, "-----post----mIsEncoding------" + mIsEncoding);
        if(mIsEncoding)
            sendEncordSuccessBroadcast();
        mEncodeList.clear();
        mIsEncoding = false;
        mCurrentEncodeTime = 0L;
    }

    private boolean isExist(String path){
        File f = new File(path);
        if(f.exists()){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 编码线程
     */
    private class EncodeAVIToMP4Thread extends Thread{
        @Override
        public void run() {
            encoding();
        }
    }

    /**
     * 将所有没有编码的视频加入到列表中
     */
    private void _addNoAVIToMP4(){
        File oldFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/lipeibao/168cardev/video");

        if (oldFile.isDirectory()) {
            File[] childFiles = oldFile.listFiles();
            for (int i = 0; i < childFiles.length; i++) {
                String path = childFiles[i].getAbsolutePath();
                String filename = childFiles[i].getName();
                if(filename.contains(".avi")){
                    String name = filename.substring(0,filename.indexOf("."));
                    File mp4name = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/lipeibao/168cardev/mp4/" + name + ".mp4");
                    if(!mp4name.exists())
                        mEncodeList.add(path);
                }
            }
        }
    }
}
